package com.jic.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.manager.entity.TTemplate;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.mapper.TTemplateMapper;
import com.jic.manager.request.TTemplateRequest;
import com.jic.manager.response.TTemplateResponse;
import com.jic.manager.service.TTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class TTemplateServiceImpl implements TTemplateService {

    @Resource
    private TTemplateMapper mapper;


    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(TTemplate request) {
        int flag = mapper.insert(request);
        if (flag == 1) {
            return 1;
        } else {
            return -1;
        }
    }



    /**
     * 模板新增
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public RestResult saveTemplate(TTemplateRequest request) {
        log.info("保存短信或邮件模板： 请求参数=============>>>>{}", JSONArray.toJSONString(request));
        try {
            // templateType 1.短信模板2.邮件模板
            TTemplate tTemplate = new TTemplate();
            BeanUtils.copyProperties(request, tTemplate);
            tTemplate.setCreator(null!=request.getAdminOperate()?request.getAdminOperate().getOperator():0);
            tTemplate.setCreatorName(null!=request.getAdminOperate()?request.getAdminOperate().getOperateName():"");
            tTemplate.setDeptId(request.getAdminOperate().getDeptId());
            tTemplate.setDeptType(request.getAdminOperate().getDeptType().getCode());
            mapper.insert(tTemplate);
        } catch (Exception e) {
            log.error("模板新增失败:{}", e);
            return  RestResult.error("9999",e.getMessage());
        }
        return RestResult.success(Boolean.TRUE);
    }



    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(TTemplateRequest request) {
        TTemplate tTemplate = new TTemplate();
        BeanUtils.copyProperties(request, tTemplate);
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
//                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                tTemplate.setUpdater(null!=request.getAdminOperate()?request.getAdminOperate().getOperator():0);
                tTemplate.setUpdaterName(null!=request.getAdminOperate()?request.getAdminOperate().getOperateName():"");
                int flag = mapper.updateByPrimaryKey(tTemplate);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                tTemplate.setCreator(null!=request.getAdminOperate()?request.getAdminOperate().getOperator():0);
                tTemplate.setCreatorName(null!=request.getAdminOperate()?request.getAdminOperate().getOperateName():"");
                int flag = mapper.insertSelective(tTemplate);
                if (flag == 1) {
                    return 1;
                } else {
//                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
//            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(TTemplate request) {
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
//            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
            return  -1;
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(TTemplate request) {
        request.setDeleteFlag(1);
        int flag = mapper.updateByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
//            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
            return  -1;
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(TTemplateRequest request) {
        try {
            log.info("修改记录");
            TTemplate param = new TTemplate();
            BeanUtils.copyProperties(request, param);
            param.setUpdater(null!=request.getAdminOperate()?request.getAdminOperate().getOperator():0);
            param.setUpdaterName(null!=request.getAdminOperate()?request.getAdminOperate().getOperateName():"");
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
//                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
                return  -1;
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
//            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            return  -1;
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public TTemplate getByPrimaryKey(TTemplateRequest request) {
        TTemplate param = new TTemplate();
        BeanUtils.copyProperties(request, param);
        return mapper.selectByPrimaryKey(param);
    }


    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<TTemplate> listAllRecord(TTemplateRequest request) {
        //分页处理
        TTemplate param = new TTemplate();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        return mapper.selectBySelective(param);
    }


    /**
     * 分页查询
     *
     * @param request 分页查询入参实体类
     * @return 含有分页信息的实体类列表
     */
    @Override
    public PageResult<TTemplateResponse> listPageBySelective(TTemplateRequest request) {
        TTemplate param = new TTemplate();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        //计算下标
        int startIndex = (request.getStart() - 1) * request.getLimit();
        List<TTemplate> list = mapper.listPageBySelective(param, startIndex, request.getLimit());
        Long count = mapper.listPageBySelectiveCount(param);
        List<TTemplateResponse> responseList = list.stream().map(temp -> {
            TTemplateResponse bo = new TTemplateResponse();
            BeanUtils.copyProperties(temp, bo);
            return bo;
        }).filter(item -> item != null).collect(Collectors.toList());
        PageResult<TTemplateResponse> result = new PageResult<>();
        result.setTotal(count);
        result.setRows(responseList);
        return result;
    }

}
